package com.yjc.drygoods.cart.interceptor;

import com.yjc.common.constant.AuthServerConstant;
import com.yjc.common.constant.CartServerConstant;
import com.yjc.common.vo.MemberRespVo;
import com.yjc.drygoods.cart.to.UserInfoTo;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;

/**
 * @author yjc
 * @create 2022-09-21 19:11
 */
@Component
public class CartInterceptor implements HandlerInterceptor {

    public static ThreadLocal<UserInfoTo> threadLocal = new ThreadLocal<>();


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {


        UserInfoTo userInfoTo = new UserInfoTo();

        HttpSession session = request.getSession();
        MemberRespVo memberRespVo = (MemberRespVo) session.getAttribute(AuthServerConstant.LOGIN_USER);
        if (memberRespVo != null) {
            //已登录
            userInfoTo.setUserId(memberRespVo.getId());
        }
        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                String cookieName = cookie.getName();
                if (CartServerConstant.TEMPER_USER_KEY.equals(cookieName)) {
                    userInfoTo.setUserKey(cookie.getValue());
                    userInfoTo.setIsTemper(true);
                    break;
                }
            }
        }

        if (!userInfoTo.getIsTemper()) {
            String userKey = UUID.randomUUID().toString().replace("-", "");
            userInfoTo.setUserKey(userKey);
        }

        threadLocal.set(userInfoTo);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        UserInfoTo userInfoTo = threadLocal.get();
        if (!userInfoTo.getIsTemper()) {
            Cookie cookie = new Cookie(CartServerConstant.TEMPER_USER_KEY, userInfoTo.getUserKey());
            cookie.setDomain("drygoods.top");
            cookie.setMaxAge(CartServerConstant.TEMPER_USER_KEY_TIMEOUT);
            response.addCookie(cookie);
        }
    }
}
